<template>
  <div class="upload" v-loading="uploadLoading">
    <img v-if="isshow && cover" :src='cover' style="width: 35px; height: 35px; margin-right: 2%; line-height: 35px">
    <div v-if="isshow && cover" class="showimg">
      <img :src='cover' style="width: 100%; height: 100%;">
    </div>
    <el-upload class="upload-demo"
               :show-file-list="false"
               :multiple="multiple"
               ref="upload"
               action=""
               :before-upload="handleBeforeUpload"
               accept="image/*" :http-request="handleUploadImage">
      <el-button size="mini" type="primary" icon="UploadFilled">{{ uptext }}</el-button>
    </el-upload>
    <el-button v-if="showremove" style="margin-left: 10px" icon="Delete" type="danger" size="mini" @click="removeClick">
      删除
    </el-button>
  </div>
</template>
<script setup>
import {uploadFile} from "@/api/upload";
import KVA from '@/utils/kva.js'
const uploadLoading = ref(false)
const cover = ref("")
const emits = defineEmits(["success", "validate"])
const imgArr = ref([])
const props = defineProps({
  'url': {
    type: String,
    default: ''
  },
  opid: {
    type: Number,
    default: 0
  },
  path: {
    type: String,
    default: 'default'
  },
  oldName: {
    type: String,
    default: ''
  },
  uptext: {
    type: String,
    default: '上传图片'
  },
  isshow: {
    type: Boolean,
    default: true
  },
  multiple: {
    type: Boolean,
    default: false
  }
})

const removeClick = () => {
  cover.value = ""
  emits('success', '')
  imgArr.value = []
}

const toggleImgcover = (data) => {
  cover.value = data
}

const handleBeforeUpload = (file) => {
  return true;
}

const hanleChangeRemoveImgArr = () => {
  // 删除一个元素
  imgArr.value.splice(0,1)
}

// 设置验证的长度
const hanleChangeSetImgArr = (num) => {
  // 删除一个元素
  for (let i = 0; i < num; i++) {
    imgArr.value.push(i)
  }
}

const handleUploadImage = async (file) => {
  try {
    uploadLoading.value = true
    const formData = new FormData();
    formData.append('file', file.file);
    const resp = await uploadFile(formData,props.path,props.oldName)
    emits('success', resp.data.url,resp.data)
    cover.value = resp.data.url
    uploadLoading.value = false
  }catch (e) {
    uploadLoading.value = false
    KVA.error("上传失败...")
  }
}

defineExpose({
  toggleImgcover,
  removeClick,
  hanleChangeRemoveImgArr,
  hanleChangeSetImgArr
})

</script>

<style lang="scss" scoped>
.upload {
  display: flex;
  align-items: center;
  position: relative;
}

.upload > img:hover + .showimg {
  display: block;
}

.showimg {
  width: 360px;
  height: 300px;
  position: absolute;
  padding: 5px;
  background: #ccc;
  top: 0px;
  left: 40px;
  z-index: 1;
  display: none;
}
</style>
